package com.fable.ntzw_ga.controller;


import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fable.common.config.RabbitConfig;
import com.fable.common.constants.CommonConstant;
import com.fable.common.eunm.AppHttpCodeEnum;
import com.fable.common.vo.ResultVO;
import com.fable.ntzw_ga.entity.ChatMsg;
import com.fable.ntzw_ga.service.IChatMsgService;
import com.fable.ntzw_ga.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author Created by gzh 2023-03-25 12:46:14
 */
@Api(tags = "消息发送")
@RestController
@RequestMapping("/ntzw_ga/chat-msg")
@Slf4j
public class ChatMsgController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    ISysUserService sysUserService;

    @Autowired
    IChatMsgService chatMsgService;

    @ApiOperation(value = "消息发送接口")
    @PostMapping(value = "/send")
    public ResultVO defaultMessage(@RequestBody ChatMsg chatMsg) {
        chatMsg.setCreated(LocalDateTime.now());
        chatMsg.setDir(CommonConstant.RIGHT);
        rabbitTemplate.convertAndSend(RabbitConfig.DEFAULT_EXCHANGE, "", JSONObject.toJSONString(chatMsg));
        log.info("以向"+chatMsg.getToUsername()+"发送数据:{}", chatMsg.getContent());
        //对未读消息处理from_username
        LambdaQueryWrapper<ChatMsg> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatMsg::getToUsername,chatMsg.getFromUsername());
        List<ChatMsg> chatMsgs = chatMsgService.list(wrapper);
        chatMsgs.forEach(chatMsg1 -> chatMsg1.setStatus(true));
        //批量修改消息状态
        chatMsgService.saveOrUpdateBatch(chatMsgs);
        chatMsgService.save(chatMsg);
        return ResultVO.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @ApiOperation(value = "查询本地没有处理的消息")
    @PostMapping(value = "/selectMessage")
    public ResultVO selectMessage(@RequestBody ChatMsg chatMsg) {
        LambdaQueryWrapper<ChatMsg> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatMsg::getFromNickname,chatMsg.getFromNickname()).orderByAsc(ChatMsg::getCreated);
        List<ChatMsg> msgList = chatMsgService.list(wrapper);
        return ResultVO.okResult(msgList);
    }
}
